package com.frxuexi.apps.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.apps.intent.NewsIntent
import com.frxuexi.apps.model.NewsState
import com.frxuexi.apps.repository.NewsRepository
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class NewsViewModel:ViewModel() {

    val newsRepository by lazy { NewsRepository() }

    //创建一个存放意图的管道
    val newsChannel=Channel<NewsIntent>(Channel.UNLIMITED)

    //声明一个可变状态流
    private var _newsState=MutableStateFlow<NewsState>(NewsState.onLoading)
    //用于外界访问的状态，不可变
    val newsState:StateFlow<NewsState>
        get() = _newsState

    init {
        viewModelScope.launch {
            newsChannel.consumeAsFlow().collect{
                when(it){
                    is NewsIntent.getNews->
                        getNews(it.type)
                        else->{}
                }
            }
        }
    }

    private fun getNews(type: Int) {
        viewModelScope.launch {
            newsRepository.getNews(type).collect{
                if(it.code==0){
                    _newsState.value=NewsState.onSuccess(it.data.records)
                }else{
                    _newsState.value=NewsState.onError(it.msg)
                }
            }
        }
    }


}